import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Text, Vibration } from 'react-native';
import { Icon, List, ListItem, Button, SideMenu, SearchBar } from 'react-native-elements';
import Loader from './widgets/Loader';
import { primaryColor, toast, executor } from './utils';
import { printReceipt } from './printerUtils'; 

const styles = StyleSheet.create({
  searchHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  fill: {
    flex: 1,
  },
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  button: {
    paddingTop: 32
  },
  bagNotFound: {
    color: 'red'
  },
  list: {
    marginTop: 0
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  header: {
    padding: 8
  },
  checked: {
    color: '#4CAF50'
  },
  selected: {
    color: primaryColor
  },
  orderNumber: {
    color: '#795548'
  },
  iconLeft: {
    marginLeft: 16
  },
  preview: {
    height: 50
  },
  business: {
    color: '#2196F3'
  }
});

class AssignFactoryPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    const { selectFactory, selects, date } = navigation.state.params||{};

    return {
      title: screenProps.chinese?`洗衣完成`:`Laundry Complete`,
      tabBarLabel: screenProps.chinese?`洗衣完成`:`Complete`,
      tabBarIcon: ({tintColor}) => <Icon name='local-laundry-service' color={tintColor} size={24}/>
    };
  }
  state = { completeOrders: [] }
  onPrint = () => {
    const completeOrders = this.state.completeOrders;
    if (completeOrders.length===0) return toast(this.props.screenProps.chinese?`打印列表为空`:`Print List is empty`);

    printReceipt(completeOrders, this.props.worker, this.props.screenProps.chinese)
  }
  onSearchChange=(data)=>{
    this.setState({inputNumner:data});
  }
  handleBarCodeRead = () => {
    let data=this.state.inputNumner;
      const chinese = this.props.screenProps.chinese;

      executor(this.props.loadOrder, data)
        .then(({res, err}) => {
          this.setState({loading: false});
          if (res&&res.loadOrder) {
            const details = res.loadOrder.pricing.details.filter((item, index) => item.productId&&(res.loadOrder.pricing.details.findIndex(detail=>detail.productName===item.productName)===index));

            Alert.alert(
              chinese?`${res.loadOrder.userRef.firstName} #${res.loadOrder.displayId}`:`${res.loadOrder.userRef.firstName} #${res.loadOrder.displayId}`,
              details.map(detail => `${detail.productName} x ${res.loadOrder.pricing.details.filter(item=>item.productName===detail.productName).map(item=>item.quantity-(item.examptQuantity||0)).reduce((a,b)=>a+b)}`).join('; '),
              [
                {text: chinese?'取消':'Cancel'},
                {text: chinese?'确认':'Confirm', onPress: () => {
                  executor(this.props.laundryComplete, data)
                    .then(({res, err}) => {
                      this.setState({loading: false});
                      if (res&&res.laundryComplete) {
                        const found = this.state.completeOrders.find(order=>order.id===res.laundryComplete.id);
                        if (found) {
                          Alert.alert(
                            chinese?`订单#${found.displayId}已经添加`:`Order #${found.displayId} Already Added`,
                            null,
                            [
                              {text: chinese?'知道了':'OK'},
                            ],
                            { cancelable: true }
                          );
                        } else {
                          this.setState({completeOrders: [res.laundryComplete, ...this.state.completeOrders]});
                        }
                      } else if (err) {
                        Alert.alert(
                          err,
                          null,
                          [
                            {text: chinese?'知道了':'OK'},
                          ],
                          { cancelable: true }
                        );
                      }
                    });
                  toast(`Updating #${data}`);
                  this.setState({loading: true});
                }},
              ],
              { cancelable: true }
            );
          }
        });

      toast(`Loading #${data}`);
      this.setState({inputNumner:null, loading: true});
  }
  render() {
    const chinese = this.props.screenProps.chinese;
    const { completeOrders, inputNumner, loading } = this.state;

    return (
      <ScrollView style={styles.container}>
        <View style={styles.searchHeader}>
          <View style={{flex:1}}>
          <SearchBar inputStyle={{height:50}} lightTheme keyboardType='numeric' value={this.state.inputNumner} showLoadingIcon={loading}
            onChangeText={this.onSearchChange} value={inputNumner} placeholder='Order number...' />
            </View>
          <Button title={chinese?'搜索':'Search'} backgroundColor={primaryColor} onPress={this.handleBarCodeRead}/>          
        </View>
        <List containerStyle={styles.list}>
          {completeOrders&&completeOrders.map(({id, displayId, status, userRef, pricing}, index) => {
            const details = pricing.details.filter((item, index) => item.productId&&(pricing.details.findIndex(detail=>detail.productName===item.productName)===index));

            return <ListItem key={index} title={`#${displayId} (${userRef.firstName})`} hideChevron subtitleStyle={{color:'green'}}
              subtitle={details.map(detail => `${detail.productName} x ${pricing.details.filter(item=>item.productName===detail.productName).map(item=>item.quantity-(item.examptQuantity||0)).reduce((a,b)=>a+b)}`).join('; ')} rightIcon={{name:'delete-forever'}}/>
          })}
        </List>
        <Button title={chinese?'打印':'Print'} onPress={this.onPrint}/>
      </ScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    query LaundryCompletePage {
      worker {
        id
        firstName
        lastName
      }
    }
  `, {
    props: ({data: {worker, loading}}) => {
      return {
        worker
      };
    }
  }),
  graphql(gql`
    mutation loadOrder($idOrBag:String!) {
      loadOrder(idOrBag:$idOrBag) {
        id
        displayId
        userRef {
          firstName
        }
        status {
          statusId
        }
        pricing {
          details {
            productId
            quantity
            examptQuantity
            productName
          }
        }
      }
    }
  `, {
    name: 'loadOrder',
    props: ({loadOrder}) => {
      return {
        loadOrder: (idOrBag) => loadOrder({variables:{idOrBag}})
      };
    }
  }),
  graphql(gql`
    mutation laundryComplete($orderNumber:Int!) {
      laundryComplete(orderNumber:$orderNumber) {
        id
        displayId
        userRef {
          firstName
        }
        status {
          statusId
        }
        pricing {
          details {
            productId
            quantity
            examptQuantity
            productName
          }
        }
      }
    }
  `, {
    name: 'laundryComplete',
    props: ({laundryComplete}) => {
      return {
        laundryComplete: (orderNumber) => laundryComplete({variables:{orderNumber}})
      };
    }
  })
)(AssignFactoryPage);

